package cn.lger.controller;

import cn.lger.dao.UserDao;
import cn.lger.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Code that Changed the World
 * Pro said
 *
 * @author Pro
 * @date 2018-03-13
 */
@Controller
public class HelloController {

    @Resource
    private UserDao userDao;

    /**
     * 硬编码方式传输数据到模板引擎渲染
     * @return ModelAndView 实体视图类
     */
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public ModelAndView hi(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> users = new ArrayList<>();
        users.add(new User("zhangsan", "123"));
        users.add(new User("lisi", "1234"));
        users.add(new User("wangwu", "12345"));
        modelAndView.setViewName("/hello.btl");
        modelAndView.addObject("users", users);
        return modelAndView;
    }

    @GetMapping("/hello")
    public String hello(Model model){

        List<User> users = userDao.findAll();
        //将users添加到modelAndView中，Spring底层会将这个Object加入httpRequest中
        model.addAttribute("users", users);
        return "/hello.btl";
    }

    @GetMapping("/save")
    public String save(){
        return "/save.btl";
    }

    @PostMapping("/save")
    public String saveUser(User user){
        userDao.save(user);
        //SpringMVC框架如果需要重定向则在前面加入redirect:即可
        return "redirect:/hello";
    }

    @GetMapping("/test")
    public String test(){
        return "/test.html";
    }

    @GetMapping("/qianduan")
    public String qianduan(){
        return "/qianduan.btl";
    }

    @GetMapping("/qianduanlogin")
    public String qianduanlogin(){
        return "/qianduanlogin.btl";
    }
}
